// 高阶组件，处理数据和扩展功能， 同寒春班；
import React, {useState, useEffect, useMemo} from 'react';
import {usePersistFn} from 'ahooks';

import DetailCard from '~/page/FineBi/common/DetailCard';
import CommonCard from '~/page/FineBi/common/CommonCard';
import DetailModal from '~/page/FineBi/common/DetailModal';
import Loading from '~/page/FineBi/common/Loading';

import {parseDimensionAndValues} from '~/page/FineBi/utils/convert';
import {queryValues, queryDetail, download} from '~/service/refundReport';
import {CODE_7001} from '~/service/http';

const defaultPager = {
    pageNum: 1,
    pageSize: 20,
    count: 0
};

const withPannel = (Element, isTable) => props => {
    // 数据格式有问题需要传过来unitId, 否则没法取，需要unitId来获取unitId obj
    const {dimensionAndValues, dId, unitId, fetchData, hidenColumnsConfig = [], userRoundValue} = props;
    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [title, setTitle] = useState();

    // 下钻
    const [drilingList, setDrilingList] = useState([]);

    // 详情数据
    const [detailData, setDetailData] = useState({});

    const [dataSource, setDataSource] = useState();
    const [pagerState, setPagerState] = useState({...defaultPager});

    const pDimensionAndValues = useMemo(() => parseDimensionAndValues((dimensionAndValues || []), dId), [
        dimensionAndValues,
        dId
    ]);

    // 获取本块数据value
    const getData = (pDimensionAndValues, drilingList, pager = defaultPager) => {
        const dashBoard = [
            {
                dashBoardName: dId,
                dashBoardId: dId
            }
        ];
        const hiddenColumns = userRoundValue === 1
            ? hidenColumnsConfig.map(([fieldId, fieldType]) => ({
                fieldId,
                fieldType
            }))
            : [];

        const param = {
            dimensionAndValues: pDimensionAndValues,
            dashBoardList: dashBoard,
            drilingList,
            pager,
            hiddenColumns
        };
        setLoading(true);

        (fetchData || queryValues)(param)
            .then(res => {
                const cardDetail = res?.data[dId];
                if (isTable) {
                    const {unitName} = cardDetail?.[`${unitId}`] || {};
                    setTitle(unitName);
                    setDataSource(cardDetail);
                    setPagerState(res?.pager || defaultPager);
                }
                else {
                    const {unitName, chart, config} = cardDetail?.[`${unitId}`] || {};
                    setTitle(unitName);
                    setDataSource({
                        chart,
                        config
                    });
                }

            })
            .finally(code => {
                // 后端限流，啥也不操作
                if (code === CODE_7001) {
                    // return;
                }
                setLoading(false);
            });
    };

    const handleDownload = () => {
        const params = {
            unitId,
            drilingList,
            dimensionAndValues: pDimensionAndValues
        };
        const excelName = title ? title : null;
        download(params, excelName);
    };

    const handleDetail = () => {
        setModalVisible(true);
        const params = {
            unitId,
            drilingList,
            dimensionAndValues: pDimensionAndValues
        };
        queryDetail(params).then(res => {
            const {data} = res;
            setDetailData(data);
        });
    };

    // 下钻
    const handleDrilling = usePersistFn(params => {
        const {info} = params;
        const {config = {}} = dataSource;
        const {dimensionList = []} = config;
        const [firstDimension] = dimensionList;
        const {dimensionId = '', dimensionName = ''} = firstDimension || {};
        const driling = {
            unitId,
            unitName: title,
            value: info?.name,
            dimensionId,
            dimensionName
        };
        setDrilingList([driling]);
    });

    const handleBack = () => {
        setDrilingList([]);
    };

    useEffect(() => {
        if (pDimensionAndValues && drilingList) {
            getData(pDimensionAndValues, drilingList);
        }
    }, [pDimensionAndValues, drilingList]);

    const handlePagerChange = usePersistFn((page, pageSize) => {
        const pager = {
            pageNum: page,
            pageSize
        };

        getData(pDimensionAndValues, drilingList, pager);
    });

    return (
        <div>
            <CommonCard
                title={title}
                style={{height: '100%'}}
                // span={6}
                loading={loading}
                content={(
                    <Element
                        {...props}
                        dataSource={dataSource}
                        pager={pagerState}
                        onDrilling={handleDrilling}
                        onPagerChange={handlePagerChange}
                    />
                )}
            />
            {/* <DetailCard
                style={{height: '100%'}}
                title={title}
                // onDownload={handleDownload}
                // onDetail={handleDetail}
                // onBack={handleBack}
                // showBack={drilingList?.length !== 0}
            >
                <Loading loading={loading}>
                    <Element {...props} dataSource={dataSource} onDrilling={handleDrilling} />
                </Loading>
            </DetailCard> */}
            <DetailModal data={detailData} detailModalVisible={modalVisible} onCancel={() => setModalVisible(false)} />
        </div>
    );
};

export default withPannel;
